<?php

namespace App\Jobs;

use App\Models\Buy;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class BuyDone implements ShouldQueue
{
  use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

  protected $buy;
  protected $retry;

  public function __construct(Buy $buy, $retry = 1)
  {
    $this->buy = $buy;
    $this->retry = $retry;
  }

  /**
   * Execute the job.
   *
   * @return void
   */
  public function handle()
  {
    $response = \Http::post(
      $this->buy->callback_url,
      // 'http://106.13.74.212:9000/api/test',
      [
        'code' => 1,
        'message' => 'ok',
        'data' => $this->buy->toArray(),
        'sign' => md5($this->buy->id . $this->buy->transaction_id . $this->buy->seller->api_token)
      ]
    );
    $text = $response->getBody()->getContents();
    if ($text === 'ok' || $this->retry >= 4) {
      return;
    }

    $delayMinutes = [1, 5, 10, 30][$this->retry - 1];

    self::dispatch($this->buy, $this->retry++)
      ->delay(now()->addMinutes($delayMinutes));
  }
}
